package com.spring.controller;

import com.spring.pojo.Talen;
import com.spring.pojo.User;
import com.spring.respone.ApiRestResponse;
import com.spring.service.TableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/page")
public class InfoController {

    @Autowired
    TableService tableService;


    @PostMapping("/insert")
    public ApiRestResponse insertInfo(@RequestBody(required = false) Talen talen,HttpServletRequest request) {
        System.out.println(request.getSession().getId());
        if (talen.getUid()==0) {
            User user = (User) request.getSession().getAttribute("user");
            talen.setUid(user.getUid());
            tableService.insert(talen);
            return ApiRestResponse.success();
        }else {

            User user = (User) request.getSession().getAttribute("user");
            talen.setUid(user.getUid());
            int ok = tableService.update(talen);
            if(ok>=1){
                return ApiRestResponse.success().setStatus(1);
            }else{
                return ApiRestResponse.success().setStatus(0);
            }
        }

    }


    @ResponseBody
    @GetMapping("/selectAll")
    public ApiRestResponse selectAll(HttpServletRequest request, HttpServletResponse response) {

        List<Talen> talenList = tableService.selectAll();
        return ApiRestResponse.success(talenList);
    }

    @CrossOrigin
    @PostMapping("/selectPersonal")
    public ApiRestResponse selectPersonalInfo(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        Talen talen = tableService.selectById(user.getUid()) ;
        if(talen==null){
            talen = new Talen();
            return ApiRestResponse.success();
        }
        else return ApiRestResponse.success(talen);

    }

    @PostMapping("/updateStatus")
    public ApiRestResponse updateStatus(@RequestBody(required = false) Talen talen,HttpServletRequest request){
        int ok = tableService.update(talen) ;
        if(ok>=1){
            return ApiRestResponse.success().setStatus(1) ;
        }else{
            return ApiRestResponse.error().setStatus(0) ;
        }
    }
}
